package com.xuecheng.teaching.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.teaching.feignclient.ContentClient;
import com.xuecheng.teaching.mapper.TeachplanWorkMapper;
import com.xuecheng.teaching.mapper.WorkMapper;
import com.xuecheng.teaching.mapper.WorkRecordMapper;
import com.xuecheng.teaching.model.dto.WorkRecGroupDTO;
import com.xuecheng.teaching.model.dto.WorkRecOverallDTO;
import com.xuecheng.teaching.model.dto.WorkRecordDTO;
import com.xuecheng.teaching.model.dto.WorkRecordStatsDTO;
import com.xuecheng.teaching.model.entity.TeachplanWork;
import com.xuecheng.teaching.model.entity.WorkRecord;
import com.xuecheng.teaching.model.vo.WorkRecordPageListVO;
import com.xuecheng.teaching.model.vo.WorkRecordPageVO;
import com.xuecheng.teaching.service.WorkRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WorkRecordServiceImpl implements WorkRecordService {

    @Resource
    private WorkRecordMapper workRecordMapper;

    @Resource
    private WorkMapper workMapper;
    @Autowired
    private ContentClient contentClient;

    @Autowired
    private TeachplanWorkMapper teachplanWorkMapper ;
    @Override
    @Transactional
    public Boolean submitWork(WorkRecordDTO workRecordDTO) {
        // 参数校验
        if (workRecordDTO == null || workRecordDTO.getWorkId() == null
                || StringUtils.isEmpty(workRecordDTO.getAnswer())) {
            throw new XueChengPlusException("提交信息不完整");
        }

        // 查询是否已存在提交记录
        LambdaQueryWrapper<WorkRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkRecord::getWorkId, workRecordDTO.getWorkId())
                .eq(WorkRecord::getUsername, workRecordDTO.getUsername());
        WorkRecord existingRecord = workRecordMapper.selectOne(queryWrapper);

        WorkRecord workRecord;
        if (existingRecord != null) {

            // 更新已有记录
            workRecord = existingRecord;
            workRecord.setAnswer(workRecordDTO.getAnswer());
            workRecord.setStatus("306001"); // 重新设置为待批阅
            workRecord.setCreateDate(LocalDateTime.now());
            workRecordMapper.updateById(workRecord);

        } else {
            // 创建新记录
            workRecord = new WorkRecord();
            BeanUtils.copyProperties(workRecordDTO, workRecord);
            workRecord.setStatus("306001"); // 设置为待批阅
            workRecord.setCreateDate(LocalDateTime.now());
            workRecordMapper.insert(workRecord);
        }

        return true;
    }
    @Override
    public WorkRecordDTO getWorkStatus(Long workId, Long coursePubId, String username) {
        // 构建查询条件
        LambdaQueryWrapper<WorkRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkRecord::getWorkId, workId)
                .eq(WorkRecord::getUsername, username);

        // 查询作业记录
        WorkRecord workRecord = workRecordMapper.selectOne(queryWrapper);
        if (workRecord == null) {
            return null;
        }

        // 转换为DTO
        WorkRecordDTO dto = new WorkRecordDTO();
        BeanUtils.copyProperties(workRecord, dto);
        return dto;
    }



    @Override
    public List<WorkRecordDTO> queryWorkRecords(Long coursePubId) {
        List<WorkRecord> workRecords = workRecordMapper.selectByCoursePubId(coursePubId);
        // 将WorkRecord转换为WorkRecordDTO
        return workRecords.stream().map(workRecord -> {
            WorkRecordDTO workRecordDTO = new WorkRecordDTO();
            BeanUtils.copyProperties(workRecord, workRecordDTO);
            return workRecordDTO;
        }).collect(Collectors.toList());
    }

    @Override
    public Integer queryToBeReviewedCount(Long coursePubId) {
        return workRecordMapper.selectToBeReviewedCount(coursePubId);
    }

    @Override
    public WorkRecordPageListVO getWorkRecordList(Integer pageNo, Integer pageSize, String courseName) {
        WorkRecordPageListVO pageListVO = new WorkRecordPageListVO();
        List<WorkRecordPageVO> items = new ArrayList<>();

        List<Map<String, Object>> courseStats = workRecordMapper.selectWorkRecordStatsByCourse(
                courseName, (pageNo - 1) * pageSize, pageSize
        );

        for (Map<String, Object> stat : courseStats) {
            WorkRecordPageVO vo = new WorkRecordPageVO();
            vo.setCourseName((String) stat.get("courseName"));

            // 安全的类型转换
            Object totalUsers = stat.get("totalUsers");
            if (totalUsers instanceof Long) {
                vo.setTotalUsers((Long) totalUsers);
            } else if (totalUsers instanceof BigDecimal) {
                vo.setTotalUsers(((BigDecimal) totalUsers).longValue());
            } else if (totalUsers instanceof Integer) {
                vo.setTotalUsers(((Integer) totalUsers).longValue());
            }

            Object tobeReviewed = stat.get("tobeReviewed");
            if (tobeReviewed instanceof Long) {
                vo.setTobeReviewed((Long) tobeReviewed);
            } else if (tobeReviewed instanceof BigDecimal) {
                vo.setTobeReviewed(((BigDecimal) tobeReviewed).longValue());
            } else if (tobeReviewed instanceof Integer) {
                vo.setTobeReviewed(((Integer) tobeReviewed).longValue());
            }

            vo.setCommitedTime((LocalDateTime) stat.get("lastCommitTime"));
            vo.setReviewedTime((LocalDateTime) stat.get("lastReviewTime"));
            vo.setCourseWorkId((Long) stat.get("courseWorkId"));
            items.add(vo);
        }



        // 设置分页信息
        long total = workRecordMapper.countWorkRecordStatsByCourse(courseName);
        pageListVO.setItems(items);
        pageListVO.setCounts(total);
        pageListVO.setFirst(pageNo == 1);
        pageListVO.setItemsSize(items.size());
        pageListVO.setPage(pageNo);
        pageListVO.setPages((int) Math.ceil(total * 1.0 / pageSize));
        pageListVO.setPageSize(pageSize);
        return pageListVO;
    }
    @Override
    public WorkRecOverallDTO getWorkRecordReadOverAll(Long courseWorkId) {
        TeachplanWork teachplanWork = teachplanWorkMapper.selectByWorkId(courseWorkId);
       if (teachplanWork==null)
       {
           XueChengPlusException.cast("作业提交记录为空");
       }
        Long courseId = teachplanWork.getCourseId();
        // 查询课程信息
        CourseBase courseBase = contentClient.getCourseBase(courseId);
        if (courseBase == null) {
            throw new RuntimeException("课程不存在");
        }

        WorkRecOverallDTO overallDTO = new WorkRecOverallDTO();
        overallDTO.setCourseName(courseBase.getName());

        // 统计课程作业相关数据
        WorkRecordStatsDTO stats = workRecordMapper.selectWorkRecordStats(courseWorkId);
        overallDTO.setWorkNumber(stats.getWorkNumber());
        overallDTO.setLearnerNumber(stats.getLearnerNumber());
        overallDTO.setCommitterNumber(stats.getCommitterNumber());
        overallDTO.setAnswerNumber(stats.getAnswerNumber());
        overallDTO.setTobeReviewed(stats.getTobeReviewed());
        // 按课程计划分组查询作业记录
        List<WorkRecGroupDTO> groupList = new ArrayList<>();
        List<Teachplan> teachplanList = contentClient.getBycourseId(courseId);
        for (Teachplan teachplan : teachplanList) {
            WorkRecGroupDTO groupDTO = new WorkRecGroupDTO();
            groupDTO.setTeachplanId(teachplan.getId());
            groupDTO.setTeachplanName(teachplan.getPname());

            // 查询该课程计划下的作业记录
            List<WorkRecordDTO> recordList = workRecordMapper.selectByTeachplanId(teachplan.getId());
            groupDTO.setWorkRecordList(recordList);

            groupList.add(groupDTO);
        }
        overallDTO.setRecGroupDTOList(groupList);

        return overallDTO;
    }
    @Override
    public Boolean correctWork(WorkRecordDTO workRecordDTO) {
        // 使用已有的批改方法
        WorkRecord workRecord = workRecordMapper.selectById(workRecordDTO.getWorkRecordId());
        if (workRecord == null) {
            throw new RuntimeException("作业记录不存在");
        }

        workRecord.setCorrectComment(workRecordDTO.getCorrectComment());
        workRecord.setStatus("306002");  // 已批改状态
        workRecord.setCorrectionDate(LocalDateTime.now());
        workRecord.setScore(workRecordDTO.getScore());
        int updated = workRecordMapper.updateById(workRecord);
        return updated > 0;
    }
    }